package com.itjin.health.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itjin.health.domain.dto.AppointmentCancelRequest;
import com.itjin.health.domain.dto.OfflineAssessmentRequest;
import com.itjin.health.domain.dto.OnlineAssessmentDetailRequest;
import com.itjin.health.domain.dto.OnlineAssessmentRequest;
import com.itjin.health.domain.entity.InjuryReport;
import com.itjin.health.domain.entity.OfflineAssessmentAppointment;
import com.itjin.health.domain.entity.User;
import com.itjin.health.domain.entity.OnlineAssessmentAppointment;
import com.itjin.health.domain.vo.OfflineAppointmentDetailVO;
import com.itjin.health.domain.vo.OnlineAppointmentDetailVO;
import com.itjin.health.exception.BusinessException;
import com.itjin.health.exception.ErrorCode;
import com.itjin.health.mapper.InjuryReportMapper;
import com.itjin.health.mapper.OfflineAssessmentAppointmentMapper;
import com.itjin.health.mapper.UserMapper;
import com.itjin.health.mapper.OnlineAssessmentAppointmentMapper;
import com.itjin.health.service.AssessmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AssessmentServiceImpl extends ServiceImpl<OfflineAssessmentAppointmentMapper, OfflineAssessmentAppointment>
    implements AssessmentService {

  @Resource
  private InjuryReportMapper injuryReportMapper;

  @Resource
  private UserMapper userMapper;

  @Resource
  private OnlineAssessmentAppointmentMapper onlineAssessmentAppointmentMapper;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Integer applyOfflineAssessment(OfflineAssessmentRequest request) {
    if (request == null || request.getReportId() == null || request.getStudentId() == null
        || request.getAppointmentDate() == null || request.getAppointmentTime() == null
        || request.getLocation() == null || request.getLocation().isEmpty()) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 检查伤情报告是否存在
    InjuryReport report = injuryReportMapper.selectById(request.getReportId());
    if (report == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "伤情报告不存在");
    }

    // 检查报告是否属于该学生
    if (!report.getUserId().equals(request.getStudentId())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权操作此伤情报告");
    }

    // 检查报告状态是否为"新提交"
    if (!"新提交".equals(report.getStatus())) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "只能对'新提交'状态的报告申请评估");
    }

    // 检查预约日期是否合法（不能在过去）
    if (request.getAppointmentDate().isBefore(LocalDate.now()) ||
        (request.getAppointmentDate().isEqual(LocalDate.now())
            && request.getAppointmentTime().isBefore(LocalTime.now()))) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "预约时间不能在过去");
    }

    // 创建线下评估预约记录
    OfflineAssessmentAppointment appointment = new OfflineAssessmentAppointment();
    appointment.setReportId(request.getReportId());
    appointment.setStudentId(request.getStudentId());
    appointment.setAppointmentDate(request.getAppointmentDate());
    appointment.setAppointmentTime(request.getAppointmentTime());
    appointment.setLocation(request.getLocation());
    appointment.setStudentNote(request.getStudentNote());
    appointment.setStatus("待审核");

    // 保存预约记录
    boolean saveResult = this.save(appointment);
    if (!saveResult) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建预约失败");
    }

    // 更新报告状态和评估类型
    UpdateWrapper<InjuryReport> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id", request.getReportId());
    updateWrapper.set("status", "处理中");
    updateWrapper.set("evaluation_type", "线下评估");

    if (injuryReportMapper.update(null, updateWrapper) <= 0) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新伤情报告状态失败");
    }

    return appointment.getId();
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean cancelOfflineAppointment(AppointmentCancelRequest request) {
    if (request == null || request.getAppointmentId() == null || request.getStudentId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 检查预约是否存在
    OfflineAssessmentAppointment appointment = this.getById(request.getAppointmentId());
    if (appointment == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "预约记录不存在");
    }

    // 检查预约是否属于该学生
    if (!appointment.getStudentId().equals(request.getStudentId())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权操作此预约");
    }

    // 检查预约状态是否为"待审核"或"已确认"
    if (!"待审核".equals(appointment.getStatus()) && !"已确认".equals(appointment.getStatus())) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "只能取消'待审核'或'已确认'状态的预约");
    }

    // 更新预约状态
    appointment.setStatus("已取消");
    appointment.setRejectReason(request.getCancelReason());
    boolean updateResult = this.updateById(appointment);

    if (updateResult) {
      // 如果取消成功，将伤情报告状态恢复为"新提交"，并清除评估类型
      UpdateWrapper<InjuryReport> updateWrapper = new UpdateWrapper<>();
      updateWrapper.eq("id", appointment.getReportId());
      updateWrapper.set("status", "新提交");
      updateWrapper.set("evaluation_type", null);
      injuryReportMapper.update(null, updateWrapper);
    }

    return updateResult;
  }

  @Override
  public Page<OfflineAssessmentAppointment> listStudentAppointments(Integer studentId, String status, long current,
      long size) {
    if (studentId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    Page<OfflineAssessmentAppointment> page = new Page<>(current, size);
    QueryWrapper<OfflineAssessmentAppointment> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("student_id", studentId);

    if (status != null && !status.equals("all")) {
      queryWrapper.eq("status", status);
    }

    queryWrapper.orderByDesc("created_at");
    return this.page(page, queryWrapper);
  }

  @Override
  public OfflineAssessmentAppointment getAppointmentById(Integer appointmentId) {
    if (appointmentId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    return this.getById(appointmentId);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Integer applyOnlineAssessmentDetail(OnlineAssessmentDetailRequest request) {
    if (request == null || request.getReportId() == null || request.getStudentId() == null
        || request.getAppointmentDate() == null || request.getAppointmentTime() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 检查伤情报告是否存在
    InjuryReport report = injuryReportMapper.selectById(request.getReportId());
    if (report == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "伤情报告不存在");
    }

    // 检查报告是否属于该学生
    if (!report.getUserId().equals(request.getStudentId())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权操作此伤情报告");
    }

    // 检查报告状态是否为"新提交"
    if (!"新提交".equals(report.getStatus())) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "只能对'新提交'状态的报告申请评估");
    }

    // 检查预约日期是否合法（不能在过去）
    if (request.getAppointmentDate().isBefore(LocalDate.now()) ||
        (request.getAppointmentDate().isEqual(LocalDate.now())
            && request.getAppointmentTime().isBefore(LocalTime.now()))) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "预约时间不能在过去");
    }

    // 创建线上评估预约记录
    OnlineAssessmentAppointment appointment = new OnlineAssessmentAppointment();
    appointment.setReportId(request.getReportId());
    appointment.setStudentId(request.getStudentId());
    appointment.setAppointmentDate(request.getAppointmentDate());
    appointment.setAppointmentTime(request.getAppointmentTime());
    appointment.setDuration(request.getDuration() != null ? request.getDuration() : 30);
    appointment.setPlatform(request.getPlatform() != null ? request.getPlatform() : "腾讯会议");
    appointment.setStudentNote(request.getStudentNote());
    appointment.setStatus("待审核");

    // 保存预约记录
    boolean saveResult = onlineAssessmentAppointmentMapper.insert(appointment) > 0;
    if (!saveResult) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建预约失败");
    }

    // 更新报告状态和评估类型
    UpdateWrapper<InjuryReport> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id", request.getReportId());
    updateWrapper.set("status", "处理中");
    updateWrapper.set("evaluation_type", "线上评估");

    if (injuryReportMapper.update(null, updateWrapper) <= 0) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新伤情报告状态失败");
    }

    return appointment.getId();
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean cancelOnlineAppointment(AppointmentCancelRequest request) {
    if (request == null || request.getAppointmentId() == null || request.getStudentId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 检查预约是否存在
    OnlineAssessmentAppointment appointment = onlineAssessmentAppointmentMapper.selectById(request.getAppointmentId());
    if (appointment == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "预约记录不存在");
    }

    // 检查预约是否属于该学生
    if (!appointment.getStudentId().equals(request.getStudentId())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权操作此预约");
    }

    // 检查预约状态是否为"待审核"或"已确认"
    if (!"待审核".equals(appointment.getStatus()) && !"已确认".equals(appointment.getStatus())) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "只能取消'待审核'或'已确认'状态的预约");
    }

    // 更新预约状态
    appointment.setStatus("已取消");
    appointment.setRejectReason(request.getCancelReason());
    int updateResult = onlineAssessmentAppointmentMapper.updateById(appointment);

    if (updateResult > 0) {
      // 如果取消成功，将伤情报告状态恢复为"新提交"，并清除评估类型
      UpdateWrapper<InjuryReport> updateWrapper = new UpdateWrapper<>();
      updateWrapper.eq("id", appointment.getReportId());
      updateWrapper.set("status", "新提交");
      updateWrapper.set("evaluation_type", null);
      injuryReportMapper.update(null, updateWrapper);
      return true;
    }

    return false;
  }

  @Override
  public Page<OnlineAssessmentAppointment> listStudentOnlineAppointments(Integer studentId, String status, long current,
      long size) {
    if (studentId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    Page<OnlineAssessmentAppointment> page = new Page<>(current, size);
    QueryWrapper<OnlineAssessmentAppointment> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("student_id", studentId);

    if (status != null && !status.equals("all")) {
      queryWrapper.eq("status", status);
    }

    queryWrapper.orderByDesc("created_at");
    return new Page<OnlineAssessmentAppointment>().setRecords(
        onlineAssessmentAppointmentMapper.selectPage(page, queryWrapper).getRecords()).setTotal(page.getTotal())
        .setCurrent(page.getCurrent()).setSize(page.getSize());
  }

  @Override
  public OnlineAssessmentAppointment getOnlineAppointmentById(Integer appointmentId) {
    if (appointmentId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    return onlineAssessmentAppointmentMapper.selectById(appointmentId);
  }

  @Override
  public Page<OfflineAppointmentDetailVO> getTeacherOfflineAppointments(Integer teacherId, String status,
      long current, long size) {
    if (teacherId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    Page<OfflineAssessmentAppointment> page = new Page<>(current, size);
    QueryWrapper<OfflineAssessmentAppointment> queryWrapper = new QueryWrapper<>();

    // TODO: 如果是普通教师，只能查看分配给自己的预约 (teacherId)
    // 暂时先查询所有，后期可根据用户角色判断

    if (status != null && !status.equals("all")) {
      queryWrapper.eq("status", status);
    }

    queryWrapper.orderByDesc("created_at");
    this.page(page, queryWrapper);

    // 转换成VO对象
    Page<OfflineAppointmentDetailVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
    List<OfflineAppointmentDetailVO> voList = page.getRecords().stream().map(appointment -> {
      OfflineAppointmentDetailVO vo = new OfflineAppointmentDetailVO();
      BeanUtil.copyProperties(appointment, vo);
      // 填充学生信息
      User student = userMapper.selectById(appointment.getStudentId());
      if (student != null) {
        vo.setStudentName(student.getUsername());
        vo.setStudentNumber(student.getStudentNumber());
        vo.setStudentContact(student.getPhone() != null ? student.getPhone() : student.getEmail());
      }
      // 填充伤病报告信息
      InjuryReport report = injuryReportMapper.selectById(appointment.getReportId());
      if (report != null) {
        vo.setInjuryReportTitle(report.getTitle());
      }
      return vo;
    }).collect(Collectors.toList());
    voPage.setRecords(voList);
    return voPage;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean reviewOfflineAppointment(Integer appointmentId, Integer teacherId, Boolean approved,
      String rejectReason, String teacherNote) {
    if (appointmentId == null || teacherId == null || approved == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 检查预约是否存在
    OfflineAssessmentAppointment appointment = this.getById(appointmentId);
    if (appointment == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "预约记录不存在");
    }

    // 检查预约状态是否为"待审核"
    if (!"待审核".equals(appointment.getStatus())) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "只能审核'待审核'状态的预约");
    }

    // 参数验证
    if (!approved && (rejectReason == null || rejectReason.isEmpty())) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "拒绝时必须提供原因");
    }

    // 更新预约信息
    appointment.setTeacherId(teacherId); // 分配教师

    if (approved) {
      appointment.setStatus("已确认"); // 审核通过
      // 如果有教师备注，则更新
      if (teacherNote != null && !teacherNote.isEmpty()) {
        appointment.setTeacherFeedback(teacherNote);
      }
    } else {
      appointment.setStatus("已拒绝"); // 审核拒绝
      appointment.setRejectReason(rejectReason); // 设置拒绝原因
    }

    boolean updateResult = this.updateById(appointment);

    if (updateResult && !approved) {
      // 如果拒绝，将伤情报告状态恢复为"新提交"，并清除评估类型
      UpdateWrapper<InjuryReport> updateWrapper = new UpdateWrapper<>();
      updateWrapper.eq("id", appointment.getReportId());
      updateWrapper.set("status", "新提交");
      updateWrapper.set("evaluation_type", null);
      injuryReportMapper.update(null, updateWrapper);
    }

    return updateResult;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean completeOfflineAppointment(Integer appointmentId, Integer teacherId, String feedback) {
    if (appointmentId == null || teacherId == null || feedback == null || feedback.isEmpty()) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 检查预约是否存在
    OfflineAssessmentAppointment appointment = this.getById(appointmentId);
    if (appointment == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "预约记录不存在");
    }

    // 检查是否为此预约的教师
    if (!teacherId.equals(appointment.getTeacherId())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "只有分配的教师才能完成评估");
    }

    // 检查预约状态是否为"已确认"
    if (!"已确认".equals(appointment.getStatus())) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "只能完成'已确认'状态的预约");
    }

    // 更新预约信息
    appointment.setStatus("已完成");
    appointment.setTeacherFeedback(feedback);

    boolean updateResult = this.updateById(appointment);

    if (updateResult) {
      // 更新伤情报告状态为"已解决"
      UpdateWrapper<InjuryReport> updateWrapper = new UpdateWrapper<>();
      updateWrapper.eq("id", appointment.getReportId());
      updateWrapper.set("status", "已解决");
      injuryReportMapper.update(null, updateWrapper);
    }

    return updateResult;
  }

  @Override
  public Page<OnlineAppointmentDetailVO> getTeacherOnlineAppointments(Integer teacherId, String status, long current,
      long size) {
    if (teacherId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    Page<OnlineAssessmentAppointment> page = new Page<>(current, size);
    QueryWrapper<OnlineAssessmentAppointment> queryWrapper = new QueryWrapper<>();

    // TODO: 如果是普通教师，只能查看分配给自己的预约 (teacherId)
    // 暂时先查询所有，后期可根据用户角色判断

    if (status != null && !status.equals("all")) {
      queryWrapper.eq("status", status);
    }

    queryWrapper.orderByDesc("created_at");
    onlineAssessmentAppointmentMapper.selectPage(page, queryWrapper);

    // 转换成VO对象
    Page<OnlineAppointmentDetailVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
    List<OnlineAppointmentDetailVO> voList = page.getRecords().stream().map(appointment -> {
      OnlineAppointmentDetailVO vo = new OnlineAppointmentDetailVO();
      BeanUtil.copyProperties(appointment, vo);
      // 填充学生信息
      User student = userMapper.selectById(appointment.getStudentId());
      if (student != null) {
        vo.setStudentName(student.getUsername());
        vo.setStudentNumber(student.getStudentNumber());
        vo.setStudentContact(student.getPhone() != null ? student.getPhone() : student.getEmail());
      }
      // 填充伤病报告信息
      InjuryReport report = injuryReportMapper.selectById(appointment.getReportId());
      if (report != null) {
        vo.setInjuryReportTitle(report.getTitle());
      }
      return vo;
    }).collect(Collectors.toList());
    voPage.setRecords(voList);
    return voPage;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean reviewOnlineAppointment(Integer appointmentId, Integer teacherId, Boolean approved,
      String meetingUrl, String meetingId, String meetingPassword, String rejectReason) {
    if (appointmentId == null || teacherId == null || approved == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 检查预约是否存在
    OnlineAssessmentAppointment appointment = onlineAssessmentAppointmentMapper.selectById(appointmentId);
    if (appointment == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "预约记录不存在");
    }

    // 检查预约状态是否为"待审核"
    if (!"待审核".equals(appointment.getStatus())) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "只能审核'待审核'状态的预约");
    }

    // 参数验证
    if (approved) {
      if (meetingUrl == null || meetingUrl.isEmpty() || meetingId == null || meetingId.isEmpty()
          || meetingPassword == null || meetingPassword.isEmpty()) {
        throw new BusinessException(ErrorCode.PARAMS_ERROR, "通过时必须提供会议信息");
      }
    } else if (rejectReason == null || rejectReason.isEmpty()) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "拒绝时必须提供原因");
    }

    // 更新预约信息
    appointment.setTeacherId(teacherId); // 分配教师

    if (approved) {
      appointment.setStatus("已确认"); // 审核通过
      appointment.setMeetingUrl(meetingUrl);
      appointment.setMeetingId(meetingId);
      appointment.setMeetingPassword(meetingPassword);
    } else {
      appointment.setStatus("已拒绝"); // 审核拒绝
      appointment.setRejectReason(rejectReason); // 设置拒绝原因
    }

    boolean updateResult = onlineAssessmentAppointmentMapper.updateById(appointment) > 0;

    if (updateResult && !approved) {
      // 如果拒绝，将伤情报告状态恢复为"新提交"，并清除评估类型
      UpdateWrapper<InjuryReport> updateWrapper = new UpdateWrapper<>();
      updateWrapper.eq("id", appointment.getReportId());
      updateWrapper.set("status", "新提交");
      updateWrapper.set("evaluation_type", null);
      injuryReportMapper.update(null, updateWrapper);
    }

    return updateResult;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean completeOnlineAppointment(Integer appointmentId, Integer teacherId, String feedback) {
    if (appointmentId == null || teacherId == null || feedback == null || feedback.isEmpty()) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 检查预约是否存在
    OnlineAssessmentAppointment appointment = onlineAssessmentAppointmentMapper.selectById(appointmentId);
    if (appointment == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "预约记录不存在");
    }

    // 检查是否为此预约的教师
    if (!teacherId.equals(appointment.getTeacherId())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "只有分配的教师才能完成评估");
    }

    // 检查预约状态是否为"已确认"
    if (!"已确认".equals(appointment.getStatus())) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "只能完成'已确认'状态的预约");
    }

    // 更新预约信息
    appointment.setStatus("已完成");
    appointment.setTeacherFeedback(feedback);

    boolean updateResult = onlineAssessmentAppointmentMapper.updateById(appointment) > 0;

    if (updateResult) {
      // 更新伤情报告状态为"已解决"
      UpdateWrapper<InjuryReport> updateWrapper = new UpdateWrapper<>();
      updateWrapper.eq("id", appointment.getReportId());
      updateWrapper.set("status", "已解决");
      injuryReportMapper.update(null, updateWrapper);
    }

    return updateResult;
  }

  @Override
  public Object getAssessmentStats(String startDate, String endDate) {
    // 构建时间条件
    QueryWrapper<OfflineAssessmentAppointment> offlineQueryWrapper = new QueryWrapper<>();
    QueryWrapper<OnlineAssessmentAppointment> onlineQueryWrapper = new QueryWrapper<>();

    if (startDate != null && !startDate.isEmpty()) {
      offlineQueryWrapper.ge("appointment_date", startDate);
      onlineQueryWrapper.ge("appointment_date", startDate);
    }

    if (endDate != null && !endDate.isEmpty()) {
      offlineQueryWrapper.le("appointment_date", endDate);
      onlineQueryWrapper.le("appointment_date", endDate);
    }

    // 查询所有预约
    List<OfflineAssessmentAppointment> offlineAppointments = this.list(offlineQueryWrapper);
    List<OnlineAssessmentAppointment> onlineAppointments = onlineAssessmentAppointmentMapper
        .selectList(onlineQueryWrapper);

    // 统计数据
    int totalOfflineCount = offlineAppointments.size();
    int totalOnlineCount = onlineAppointments.size();

    // 按状态统计线下预约
    Map<String, Integer> offlineStatusStats = new HashMap<>();
    for (OfflineAssessmentAppointment appointment : offlineAppointments) {
      String status = appointment.getStatus();
      offlineStatusStats.put(status, offlineStatusStats.getOrDefault(status, 0) + 1);
    }

    // 按状态统计线上预约
    Map<String, Integer> onlineStatusStats = new HashMap<>();
    for (OnlineAssessmentAppointment appointment : onlineAppointments) {
      String status = appointment.getStatus();
      onlineStatusStats.put(status, onlineStatusStats.getOrDefault(status, 0) + 1);
    }

    // 按日期统计预约数量
    Map<String, Integer> dateStats = new HashMap<>();
    for (OfflineAssessmentAppointment appointment : offlineAppointments) {
      String date = appointment.getAppointmentDate().toString();
      dateStats.put(date, dateStats.getOrDefault(date, 0) + 1);
    }
    for (OnlineAssessmentAppointment appointment : onlineAppointments) {
      String date = appointment.getAppointmentDate().toString();
      dateStats.put(date, dateStats.getOrDefault(date, 0) + 1);
    }

    // 构建返回结果
    Map<String, Object> result = new HashMap<>();
    result.put("totalOfflineCount", totalOfflineCount);
    result.put("totalOnlineCount", totalOnlineCount);
    result.put("totalCount", totalOfflineCount + totalOnlineCount);
    result.put("offlineStatusStats", offlineStatusStats);
    result.put("onlineStatusStats", onlineStatusStats);
    result.put("dateStats", dateStats);

    return result;
  }
}